# -*- coding:utf-8 -*-
"""
订单清理服务 - 清理超时的pending订单
"""

from datetime import datetime, timedelta
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from module_admin.entity.do.order_record_do import OrderRecord
from utils.log_util import logger


class OrderCleanupService:
    """订单清理服务"""
    
    @classmethod
    async def cleanup_timeout_pending_orders(
        cls,
        db: AsyncSession,
        timeout_minutes: int = 5
    ) -> int:
        """
        清理超时的pending订单
        
        Args:
            db: 数据库会话
            timeout_minutes: 超时时间（分钟），默认5分钟
            
        Returns:
            清理的订单数量
        """
        try:
            # 计算超时时间点
            timeout_time = datetime.now() - timedelta(minutes=timeout_minutes)
            
            # 查询超时的pending订单
            query = select(OrderRecord).where(
                OrderRecord.order_status == 'pending',
                OrderRecord.create_time < timeout_time,
                OrderRecord.del_flag == '0'
            )
            result = await db.execute(query)
            timeout_orders = result.scalars().all()
            
            if not timeout_orders:
                logger.debug("没有超时的pending订单需要清理")
                return 0
            
            # 更新订单状态为failed
            for order in timeout_orders:
                update_query = update(OrderRecord).where(
                    OrderRecord.id == order.id
                ).values(
                    order_status='failed',
                    error='订单超时（agent可能崩溃或网络异常）',
                    update_time=datetime.now()
                )
                await db.execute(update_query)
                logger.warning(
                    f"⚠️ 清理超时pending订单: order_id={order.id}, "
                    f"item_id={order.item_id}, client_id={order.client_id}, "
                    f"创建时间={order.create_time}"
                )
            
            await db.commit()
            logger.info(f"✅ 已清理 {len(timeout_orders)} 个超时pending订单")
            return len(timeout_orders)
            
        except Exception as e:
            await db.rollback()
            logger.error(f"清理超时pending订单失败: {e}", exc_info=True)
            return 0
